package com.niit.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.niit.entity.Product;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;


/**
 * @author fish66
 */
@RestController
public class OrderController {

    @Autowired
    private RestTemplate restTemplate;

    /**
     * 根据id查询商品
     * @param productId  商品id
     * @return 商品信息
     */
    @RequestMapping(value = "/buy/{productId}", method = RequestMethod.GET)
    public Product findById(@PathVariable Integer productId) {
        //检查有效性
        if (productId == null) {
            throw new IllegalArgumentException("商品ID不能为空");
        }
        //返回
        return restTemplate.getForObject("http://localhost:8081/hw1/product/api/{productId}", Product.class, productId);


        /*
        // 获取完整响应
        ResponseEntity<String> response = restTemplate.getForEntity(
                "http://localhost:8081/hw1/product/api/{productId}",
                String.class,  // 直接获取字符串响应
                productId
        );
        // 记录原始JSON
        System.out.println("上游原始响应：" + response.getBody());

        // 手动反序列化
        ObjectMapper mapper = new ObjectMapper();
        try {
            // 反序列化JSON到Product对象
            Product product = mapper.readValue(response.getBody(), Product.class);
            return product;
        } catch (JsonProcessingException e) {
            throw new RuntimeException("JSON解析失败: " + e.getMessage(), e);
        }
        */
    }
}
